import json

import cv2 as cv
import numpy as np
from PIL import Image, ImageDraw, ImageFont
from fontTools.ttLib import TTFont


class LabelFont:
    @staticmethod
    def get_results_json(json_file_path):
        if json_file_path:
            with open(json_file_path, 'r') as f:
                return json.loads(f.read())
        return {}

    def __init__(self, font_path, target_path=None):
        self.font_path = font_path
        self.font_tool = TTFont(font_path)
        self.font = ImageFont.FreeTypeFont(font_path, size=800)
        self.cmap = self.font_tool['cmap'].tables[0].cmap
        self.ucmap = {v: k for k, v in self.cmap.items()}
        self.target_path = target_path

    @property
    def results_store(self) -> dict:
        if self.target_path:
            with open(self.target_path, 'r') as f:
                return json.loads(f.read())
        return {}

    def label(self):
        results = self.results_store.copy()
        for gid in self.font_tool.glyphOrder:
            if gid == '.notdef':
                continue
            k = self.ucmap[gid]
            if results.get(chr(k)):
                continue
            self._get_im(k)
            real_chr = input("输入你看到的汉字: ")
            if real_chr:
                results[chr(k)] = real_chr
            else:
                break
            with open(self.target_path, 'w') as f:
                f.write(json.dumps(results))
        return results

    def _get_im(self, k):
        image = Image.new('RGB', (1000, 1000), color=(255, 255, 255))
        draw = ImageDraw.Draw(image)
        draw.text((0, -100), chr(k), fill=(0, 0, 0), font=self.font)
        numpy_image = np.array(image)
        opencv_image = cv.cvtColor(numpy_image, cv.COLOR_RGB2BGR)
        cv.imshow('Image', opencv_image)
        cv.pollKey()


if __name__ == '__main__':
    g = LabelFont('../static/fonts/fanqie.woff2','../static/json/fanqie.json').label()
    # print(g)
